package com.ymatou.iapi.settlement.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.collections.CollectionUtils;
import org.apache.http.client.ClientProtocolException;

import com.ymatou.i.accounting.api.parameter.AccountBean;
import com.ymatou.i.accounting.api.parameter.GetAccountListByUserIdBean;
import com.ymatou.i.accounting.api.service.GetAccountListByUserIdCall;
import com.ymatou.iapi.settlement.parameter.AdRateInfoPo;
import com.ymatou.iapi.settlement.parameter.AdRateProductInfo;
import com.ymatou.iapi.settlement.parameter.GenerateAdRateInfoReq;
import com.ymatou.iapi.settlement.parameter.GenerateRefundCommissionInvoiceBean;
import com.ymatou.iapi.settlement.parameter.SettleAdCostReq;
import com.ymatou.iapi.trading.operate.parameter.Order;
import com.ymatou.iapi.trading.operate.parameter.OrderInfoPo;
import com.ymatou.iapi.trading.operate.parameter.OrderItemVo;
import com.ymatou.iapi.trading.operate.parameter.PlaceOrderResp;
import com.ymatou.iapi.trading.operate.parameter.PlaceOrderService;
import com.ymatou.iapi.trading.operate.parameter.req.PlaceOrderReq;
import com.ymttest.business.service.AccountCallService;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.database.sqlwapper.DefaultWapper;
import com.ymttest.database.sqlwapper.YmtSettlementInvoiceWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;

public class SettlementService {

	private static GenerateAdRateInfoReq generateAdRateInfoReq = new GenerateAdRateInfoReq();
	private static GenerateAdRateInfoCall generateAdRateInfoCall = new GenerateAdRateInfoCall();

	/**
	* 
	* 一次下单同一个商家1个订单分别使用平台,商家优惠券,订单下面2个商品
	* 不使用优惠券
	* 
	*/
	public static PlaceOrderResp placeOrder(int sellerId) {

		int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));

		PlaceOrderResp orderResp = new PlaceOrderResp();

		PlaceOrderReq placeorderBean = PlaceOrderService.getDefaultOrderReq();

		//不使用平台券
		placeorderBean.setYmatouCoupon(null);
		//不使用商家券
		placeorderBean.getOrderGroups().get(0).setSellerCoupon(null);

		placeorderBean.setOrderGroups(Arrays.asList(PlaceOrderService
				.getDefaultOrderGroupVo(userId, sellerId)));

		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().add(PlaceOrderService.getDefaultOrderItemVo());

		return PlaceOrderService.callPlaceOrderService(placeorderBean);
	}
	/**
	* 
	* 一次下单同一个商家1个订单分别使用平台,商家优惠券,多个商品
	* 固定 一级类目  带佣金费率
	* 
	* @param isFreightFree 是否包邮
	* 
	*/
	public static PlaceOrderResp placeOrder2(boolean isFreightFree) {

		int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
		int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));

		PlaceOrderReq placeorderBean = PlaceOrderService.getDefaultOrderReq();

		placeorderBean.setOrderGroups(Arrays.asList(PlaceOrderService
				.getDefaultOrderGroupVo(userId, sellerId)));

		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().add(PlaceOrderService.getDefaultOrderItemVo());

		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().add(PlaceOrderService.getDefaultOrderItemVo());

		int firstCataid = 1149;

		//设置没有商品的随机运费
		for (int i = 0; i < 1; i++) {

			for (int j = 0; j < 1; j++) {

				placeorderBean
						.getOrderGroups()
						.get(i)
						.getOrders()
						.get(j)
						.getOrderItems()
						.forEach(
								item -> {

									if (!isFreightFree) {

										item.setFreight(new BigDecimal(
												new Random().nextInt(50)));
									}

									item.setFirstCategoryId(firstCataid);

								});

			}

		}

		//第二个商品价格设置一个大金额，佣金收费超过最大150阀值
		OrderItemVo orderItemVo2 = placeorderBean.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(1);
		orderItemVo2.setProductPrice(new BigDecimal(3100));
		orderItemVo2.setEarnestPrice(new BigDecimal(3100));
		orderItemVo2.setOriginalPrice(new BigDecimal(3100));

		return PlaceOrderService.callPlaceOrderService(placeorderBean);
	}

	/**
	* 
	* 一次下单同一个商家1个订单分别使用平台,商家优惠券,多个商品
	* 固定 二级类目  带佣金费率
	* 
	* @param isFreightFree 是否包邮
	* 
	* 
	*/
	public static PlaceOrderResp placeOrder3(boolean isFreightFree) {

		int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
		int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));

		PlaceOrderReq placeorderBean = PlaceOrderService.getDefaultOrderReq();

		placeorderBean.setOrderGroups(Arrays.asList(PlaceOrderService
				.getDefaultOrderGroupVo(userId, sellerId)));

		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().add(PlaceOrderService.getDefaultOrderItemVo());

		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().add(PlaceOrderService.getDefaultOrderItemVo());

		int firstCategoryId = 1313;
		int secondCategoryId = 1420;

		//设置没有商品的随机运费
		for (int i = 0; i < 1; i++) {

			for (int j = 0; j < 1; j++) {

				placeorderBean
						.getOrderGroups()
						.get(i)
						.getOrders()
						.get(j)
						.getOrderItems()
						.forEach(
								item -> {

									if (!isFreightFree) {

										item.setFreight(new BigDecimal(
												new Random().nextInt(50)));
									}

									item.setFirstCategoryId(firstCategoryId);
									item.setSecondCategoryId(secondCategoryId);

								});

			}

		}

		//第二个商品价格设置一个大金额，佣金收费超过最大150阀值
		OrderItemVo orderItemVo2 = placeorderBean.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(1);
		orderItemVo2.setProductPrice(new BigDecimal(3100));
		orderItemVo2.setEarnestPrice(new BigDecimal(3100));
		orderItemVo2.setOriginalPrice(new BigDecimal(3100));

		return PlaceOrderService.callPlaceOrderService(placeorderBean);
	}
	/***
	 * 
	 * 生成一个订单多个商品广告费数据
	 * 	@param sellerId
	 * 	@param isMultiple 是否创建多个广告商品费用数据
	 * 
		*/
	public static List<AdRateInfoPo> generateAdRateInfo(int sellerId,
			boolean isMultiple) {

		List<AdRateInfoPo> adRateInfoPoList = new ArrayList<AdRateInfoPo>();

		try {

			PlaceOrderResp placeOrderResp = placeOrder(sellerId);

			Order order = placeOrderResp.getOrderList().get(0);

			int orderId = order.getOrderId();
			int userId = placeOrderResp.getUserId();
			int traidngId = placeOrderResp.getTradingId();
			BigDecimal payAmount = placeOrderResp.getPayAmount();

			new OrderCallService()
					.orderPayRequest(userId, payAmount, traidngId);

			List<OrderInfoPo> orderInfoList = order.getOrderInfoList();

			List<AdRateProductInfo> adRateProductInfoList = new ArrayList<AdRateProductInfo>();

			for (OrderInfoPo orderInfo : orderInfoList) {

				AdRateProductInfo adRateProductInfo = new AdRateProductInfo();

				BigDecimal adCostMax = new BigDecimal(
						1 + new Random().nextInt(30));

				adRateProductInfo.setProductId(orderInfo.getProductId());

				adRateProductInfo.setAdId(TestDataManager.getRandomIntNum(9));

				adRateProductInfo.setAdCostId(TestDataManager.getRandomUUID()
						.toString());

				adRateProductInfo.setAdRate(new BigDecimal(new Random()
						.nextFloat() / 10));

				adRateProductInfo.setAdCostMax(adCostMax);

				adRateProductInfoList.add(adRateProductInfo);

			}

			//不是多商品广告
			if (!isMultiple)
				adRateProductInfoList.remove(0);

			generateAdRateInfoReq.setOrderId(orderId);

			generateAdRateInfoReq.setAdProductInfos(adRateProductInfoList);

			generateAdRateInfoCall.setData(generateAdRateInfoReq);

			generateAdRateInfoCall.callService();

			adRateInfoPoList = new YmtSettlementInvoiceWapper()

			.selectYmtAdRateInfo(orderId);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return adRateInfoPoList;

	}

	/***
	 * 
	 * 生成一个订单多个商品广告费数据
	 * 	@param sellerId
	 * 	@param isMultiple 是否创建多个广告商品费用数据
	 * 
		*/
	public static List<AdRateInfoPo> generateAdRateInfo(
			PlaceOrderResp placeOrderResp, BigDecimal adRate) {

		List<AdRateInfoPo> adRateInfoPoList = new ArrayList<AdRateInfoPo>();

		try {

			//PlaceOrderResp placeOrderResp = placeOrder(sellerId);

			Order order = placeOrderResp.getOrderList().get(0);

			int orderId = order.getOrderId();
			int userId = placeOrderResp.getUserId();
			int traidngId = placeOrderResp.getTradingId();
			BigDecimal payAmount = placeOrderResp.getPayAmount();

			new OrderCallService()
					.orderPayRequest(userId, payAmount, traidngId);

			List<OrderInfoPo> orderInfoList = order.getOrderInfoList();

			List<AdRateProductInfo> adRateProductInfoList = new ArrayList<AdRateProductInfo>();

			for (OrderInfoPo orderInfo : orderInfoList) {

				AdRateProductInfo adRateProductInfo = new AdRateProductInfo();

				BigDecimal adCostMax = new BigDecimal(100);

				adRateProductInfo.setProductId(orderInfo.getProductId());

				adRateProductInfo.setAdId(TestDataManager.getRandomIntNum(9));

				adRateProductInfo.setAdCostId(TestDataManager.getRandomUUID()
						.toString());

				adRateProductInfo.setAdRate(adRate);

				adRateProductInfo.setAdCostMax(adCostMax);

				adRateProductInfoList.add(adRateProductInfo);

			}

			generateAdRateInfoReq.setOrderId(orderId);

			generateAdRateInfoReq.setAdProductInfos(adRateProductInfoList);

			generateAdRateInfoCall.setData(generateAdRateInfoReq);

			generateAdRateInfoCall.callService();

			adRateInfoPoList = new YmtSettlementInvoiceWapper()

			.selectYmtAdRateInfo(orderId);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return adRateInfoPoList;

	}

	/***
	 * 
	 * 根据用户id 查询账户信息
	 * @param userId
	 * 	
	 * 
		*/
	public static Map<Integer, AccountBean> getAccountByUserId(int userId) {

		Map<Integer, AccountBean> map = new HashMap<Integer, AccountBean>();

		try {
			GetAccountListByUserIdBean getaccountlistbyuseridBean = new GetAccountListByUserIdBean();
			GetAccountListByUserIdCall getaccountlistbyuseridCall = new GetAccountListByUserIdCall();
			getaccountlistbyuseridBean.setUserId(userId);
			getaccountlistbyuseridBean.setAppId("AutoTest");
			getaccountlistbyuseridCall.setData(false,
					getaccountlistbyuseridBean);
			getaccountlistbyuseridCall.callService();

			ArrayList<AccountBean> list = getaccountlistbyuseridCall
					.getReturnAccountList();

			if (!CollectionUtils.isEmpty(list)) {

				for (AccountBean account : list) {

					map.put(account.getAccountType(), account);

				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;

	}
	/**
	 * 
			重置 买手广告费账户
			13
			@param buyerId
			@param newAmount
	*/

	public static void resetBuyerAdvertisingFeeAccount(int buyerId,
			BigDecimal newAmount) {

		try {

			String accountid = AccountCallService.getAccountId(buyerId, 13);
			AccountCallService.resetAccount(accountid, newAmount,
					BigDecimal.ZERO);
		} catch (Exception e) {
			// TODO: handle exception

			e.printStackTrace();
		}
	}
	/**
	 * 

			重置 买手奖金池账户
			14
			@param buyerId
			@param newAmount
			
	*/
	public static void resetBuyerRewardAccount(int buyerId, BigDecimal newAmount) {

		try {
			String accountid = AccountCallService.getAccountId(buyerId, 14);

			AccountCallService.resetAccount(accountid, newAmount,
					new BigDecimal(0));

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 

			重置 买手余额账户
			1
			@param buyerId
			@param newAmount
			
	*/
	public static void resetRmbAccount(int buyerId, BigDecimal newAmount) {

		try {
			String accountid = AccountCallService.getAccountId(buyerId, 1);

			AccountCallService.resetAccount(accountid, newAmount,
					new BigDecimal(0));

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	/**
	 * 

			构造一个结算失败的订单
			14
			@return orderId
	*/
	public static long settleAdCostFail() {

		SettleAdCostReq settleAdCostReq = new SettleAdCostReq();
		SettleAdCostCall settleAdCostCall = new SettleAdCostCall();

		int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));

		//重置广告费用账户 
		resetBuyerAdvertisingFeeAccount(sellerId, BigDecimal.ONE);
		//重置广告奖金账户 
		resetBuyerRewardAccount(sellerId, new BigDecimal(2));
		//重置余额奖金账户 
		resetRmbAccount(sellerId, BigDecimal.ZERO);

		List<AdRateInfoPo> adRateInfoPoList = generateAdRateInfo(sellerId, true);

		long orderId = adRateInfoPoList.get(0).getOrderId();

		settleAdCostReq.setOrderId(orderId);

		settleAdCostCall.setData(false, settleAdCostReq);

		try {
			settleAdCostCall.callService();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return orderId;

	}

	public static void settleAdCost(int orderId) {

		SettleAdCostReq settleAdCostReq = new SettleAdCostReq();
		SettleAdCostCall settleAdCostCall = new SettleAdCostCall();

		settleAdCostReq.setOrderId(orderId);

		settleAdCostCall.setData(false, settleAdCostReq);

		try {
			settleAdCostCall.callService();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/***
	 * 	根据商家id,生成商品广告费用结算数据
		
	*/
	private static void generateSettleAdCostTestData(int sellerId) {

		SettleAdCostReq settleAdCostReq = new SettleAdCostReq();
		SettleAdCostCall settleAdCostCall = new SettleAdCostCall();

		long orderId = generateAdRateInfo(sellerId, true).get(0).getOrderId();

		settleAdCostReq.setOrderId(orderId);

		settleAdCostCall.setData(false, settleAdCostReq);

		try {
			settleAdCostCall.callService();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static BigDecimal calcRealPayAmountOnProduct(String orderInfoId) {
		BigDecimal payAmount = BigDecimal.ZERO;
		DefaultWapper defaultWapper = new DefaultWapper();

		List<Map> ymtOrderInfoList = defaultWapper
				.selectOrderInfoByOrderInfoId(orderInfoId);

		BigDecimal fProductPrice = (BigDecimal) ymtOrderInfoList.get(0).get(
				"fProductPrice");
		int iAmount = (Integer) ymtOrderInfoList.get(0).get("iAmount");
		BigDecimal fDiscount = (BigDecimal) ymtOrderInfoList.get(0).get(
				"fDiscount");
		BigDecimal fFreight = (BigDecimal) ymtOrderInfoList.get(0).get(
				"fFreight");
		BigDecimal fSellerPromotionAmount = (BigDecimal) ymtOrderInfoList
				.get(0).get("fSellerPromotionAmount");
		BigDecimal fSellerCouponAmount = (BigDecimal) ymtOrderInfoList.get(0)
				.get("fSellerCouponAmount");
		BigDecimal fYmtCouponAmount = (BigDecimal) ymtOrderInfoList.get(0).get(
				"fYmtCouponAmount");

		payAmount = fProductPrice.multiply(new BigDecimal(iAmount))
				.add(fDiscount).add(fFreight).subtract(fSellerPromotionAmount)
				.subtract(fSellerCouponAmount).subtract(fYmtCouponAmount);
		return payAmount;
	}

	public static void generateRefund(String refundBillNo) {

		GenerateRefundCommissionInvoiceBean generaterefundcommissioninvoiceBean = new GenerateRefundCommissionInvoiceBean();
		GenerateRefundCommissionInvoiceCall generaterefundcommissioninvoiceCall = new GenerateRefundCommissionInvoiceCall();

		GenerateRefundCommissionInvoiceBean.ParamExt paramExt = new GenerateRefundCommissionInvoiceBean.ParamExt();

		paramExt.setRefundBillNo(refundBillNo);
		generaterefundcommissioninvoiceBean.setParamExt(paramExt);
		generaterefundcommissioninvoiceCall.setData(false,
				generaterefundcommissioninvoiceBean);
		try {
			generaterefundcommissioninvoiceCall.callService();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String args[]) {

		//SettlementService.generateAdRateInfo(20123134, false);

		for (int i = 0; i < 10; i++) {
			SettlementService.generateSettleAdCostTestData(3383);
		}

		/*		SettlementService.resetBuyerAdvertisingFeeAccount(20123134,
						new BigDecimal(100000));*/

		SettlementService.settleAdCost(112531257);

	}
}
